/* Types of Coups */
/* Alastair Smith April 19, 2024: use residuals from Anticipating Instability project to predict the likelihood of reshuffle and regime change coups */ 

/* Update 10/22/2025 */
/* Coup data*/
/* Colpus data downloaded from https://www.johnjchin.com/colpus 4/19/2024 */
/* Cline coup data dopwnloaded https://databank.illinois.edu/datasets/IDB-8026876# on 4/19/2024 see https://clinecenter.illinois.edu/project/research-themes/democracy-and-development/coup-detat-project */
/* Powell and Thyne coup data downloaded March 2025: https://www.uky.edu/~clthyn2/coup_data/home.htm */ 

/* Nation-year and leader Data from Bueno de Mesquita and Smith Anticipating Instability data: https://dataverse.harvard.edu/dataverse/anticipatinginstability/  */ 
#delimit; 
frame change default;
clear; 
capture cd ""; /* where your files are*/

global storeresult "tablefigures"; /* specify a folder to store graphs and tables */

do "makeLabels.do"; /* a list of labels for variables */
capture program drop outgraph; program define outgraph;
graph export "${storeresult}/${name}.pdf",replace; end;

/*
/* Organize Coup Data */ 
/* Data from Chin et al */
use "2021/Coups/data/colpus/Master_Coup List_all countries_basic.dta";
sort ccode year; 
duplicates report ccode year;
/*           |         type2
      type |        CH         SH |     Total
-----------+----------------------+----------
        AD |       128         10 |       138 
        CH |       252          0 |       252 
        NM |         3         21 |        24 
        PR |        15         12 |        27 
        SH |         0        149 |       149 
        WR |         1          2 |         3 
-----------+----------------------+----------
     Total |       399        194 |       593 

	 NM=non-military
	From John Chin: Originally, we focused on two types of military coups in 
	dictatorships (per GWF autocratic regimes coding). 
	NM stood for "non-military" coup, AD stood for "anti-democratic" coups 
	(those that target democratic regimes), "PR" stood for provisional coup 
	(targeting leader of an interim / provisional regime), 
	and "WR" stood for warlord coup (targeting leader of a warlord regime). 
	CH then stood for regime change coups under dictatorships and 
	SH stood for autocratic leader reshuffling coups. 
	All of the other types were residual categories by regime type 
	we mainly ignored.

Now, in the peer review process, a reviewer pointed out and we agreed that it would make sense to extend our reshuffling/regime change distinction to all coups across all regime types and regardless of whether or not it was a military or non-military coup, and not just military coups under dictatorships, and so was born the type2 variable where we assign a regime change or reshuffling coding of CH or SH to replace the NM, AD, PR, or WR coding.
*/

/* success is code as 1 with failure as 2*/
replace success=0 if success==2;
regen chcoup=(type2=="CH"),replace;
regen shcoup=(type2=="SH"),replace;
/*regen chcoup1=(type=="CH"),replace;
regen shcoup1=(type=="SH"),replace;*/
by ccode year: egen CHcoup=max(chcoup);
by ccode year: egen SHcoup=max(shcoup);
by ccode year: egen SuccessChin=max(success);
by ccode year: egen Senior=max(srofficial);
by ccode year: egen Junior=max(jrofficer);
by ccode year: egen OutsideHelp=max(anyoutsidesupport);

/*by ccode year: egen CHcoup1=max(chcoup1);
by ccode year: egen SHcoup1=max(shcoup1);*/
tab CHcoup SHcoup;
 
duplicates tag ccode year, gen(tag); 
rename coup coupChin; rename success successChin; 

by ccode year: gen singleCoup =(_n==1); /* retain first coup only*/ 
sort ccode year; 
save   "$storeresult/chintemp.dta",replace; 
keep singleCoup SuccessChin SHcoup CHcoup  year ccode coupChin ; 
keep if singleCoup==1; 
sort ccode year; 
label var coupChin "Coup in Chin et al data";
label var CHcoup  "regime change coups in Chin et al";
label var SHcoup "Shuffle  coup in Chin et al";
label var SuccessChin "Successful Coup in Chin et al."; 

save   "$storeresult/chintempOne.dta",replace; 

 import excel "BdMSmithInstability/data/constituentdata/coup/CSPCoupsAnnualv2021.xls", sheet("Sheet1") firstrow clear; 
gen coupCSPS =0 ; replace  coupCSPS =1 if scoup1>0| atcoup2>0; 
label var coupCSPS "Successful or attempted coup in CSPS coup data";
keep ccode year coupCSPS; sort ccode year; 
save "$storeresult/CSPStemp.dta",replace; 

global replicationdata "BdMSmithInstability/bookproject/ReplicationArchiveAugust2024/empirics/data/";
use "${replicationdata}/NationYearInstability_ReplicationAugust2024.dta", clear;
keep ccode year; sort ccode year; 
merge 1:1 ccode year using  "BdMSmithInstability/data/constituentdata/coup/coupPT_march2025A.dta"; 
drop if _m==2; drop _m; 
label var AnyCoupPT "Coup in Powell and Thyne data";
label var SuccessCoupPT "Successful Coup in Powell and Thyne data";

sort ccode year;tsset ccode year;
regen coupPT01= max(AnyCoupPT, F1.AnyCoupPT), replace;
merge 1:1 ccode year using  "$storeresult/CSPStemp.dta";
drop if _m==2; drop _m; sort ccode year;


/* Merge ChinCoup data */  
merge 1:1 ccode year using "$storeresult/chintempONE.dta";
tab _m; drop _m; sort ccode year; xtset ccode year; 
replace coupChin=0 if coupChin==. &year>=1946; 
replace coupChin=. if year<1946;
 replace SuccessChin=0 if SuccessChin==. &year>=1946;
 replace CHcoup=0 if CHcoup==. &year>=1946; 
 replace SHcoup=0 if SHcoup==. &year>=1946;
regen coupChin01=(coupChin==1|F.coupChin==1),replace; 
regen CHcoup01=(CHcoup==1|F.CHcoup==1),replace;
regen SHcoup01=(SHcoup==1|F.SHcoup==1),replace;
regen SuccessChin01=(SuccessChin==1|F.SuccessChin==1),replace;
sort ccode year; 

#delimit;
merge 1:m ccode year using "$storeresult/chintemp.dta";
tab _m; drop _m;
sort ccode year;  duplicates tag ccode year, gen(multicoup);
label var multicoup "corresponds to the number of extra events in a year"; 
 global mc "& multicoup ==0";
  global ifmc " if multicoup ==0";

sort ccode year; 
save "$storeresult/COUP.dta",replace;
clear;

 
/******  Anticipating Instabtility Data. *******/
/* Load Data */
global replicationdata "BdMSmithInstability/bookproject/ReplicationArchiveAugust2024/empirics/data/";
use "${replicationdata}/NationYearInstability_ReplicationAugust2024.dta", clear;
/* Create core Variables */ 

 keep country_name year ccode v2exbribe v2excrptps v2jucorrdc v2cltort v2clkill v2peapspol v2caassemb v2x_ex_hereditary v2x_ex_military v2x_ex_party v2xcl_slave e_peaveduc LCirreg LC CountryCode wbcode country growthWB GDPpcWB lgdppcWB lpopWB polity2 growthVDEM lgdppcVDEM lpopVDEM LlpopWB LlgdppcWB LgrowthWB LlpopVDEM LlgdppcVDEM LgrowthVDEM W4 demaut Sreal S SlaveLabor Torture AccessPubGoods logIncomingTenure  revyn SICK5yB eAge IncomingTenure  ; 
sort ccode year; xtset ccode year; rename W4 W;

/* store nation-year data on policy residuals*/
save "$storeresult/NationYearData4Coups.dta",replace;
*/
use "NationYearData4Coups.dta",clear;
  regen LS=L.S; 
regen rev01= max(revyn, F1.revyn), replace;
/*health */
regen LC01=(LC==1 | F.LC==1),replace; regen LC01=. if LC==. |F.LC==.,replace;
regen LCirreg01=(LCirreg==1 | F.LCirreg==1),replace; regen LCirreg01=. if LCirreg==. |F.LCirreg==.,replace;
label var LC01 "Leader change in t or t+1";
label var LCirreg "Irregular leader change in t or t+1";

regen  LW=L.W ,replace;  regen sick=SICK5yB ,replace;
regen OldorSick=sick, replace; replace OldorSick=1 if OldorSick==0 & eAge>0;
replace OldorSick=. if sick==.|eAge==.; 
regen yr=year-2000,replace; regen yr2=yr^2,replace; regen yr3=yr^3,replace; 

/* *******************************************************************
2) CORE CONCEPTS: Coalition Welfare, Public, Private Goods. 
***********************************************************************/
/* Assembly */
sum v2caassemb; regen Assembly=(v2caassemb-r(min))/(r(max)-r(min));
regen LD3Assembly=Assembly-L3.Assembly,replace;
regen LAssembly = L.Assembly,replace;
/* Corruption: Private goods */
sum v2excrptps;
regen Corruption=1-(v2excrptps-r(min))/(r(max)-r(min)),replace;
label var Corruption "Corruption: normalized VDem v2excrptps";
regen normprivate=Corruption/exp(W+1);
sum normprivate; 
regen Private=(normprivate-r(min))/(r(max)-r(min)),replace;
label var Private "Private Goods: Corruption/exp(W+1)";
/* Public Goods */
sum v2peapspol; 
regen Public=(v2peapspol-r(min))/(r(max)-r(min)),replace; 
label var Public "Public Goods: normalized VDem v2peapspol";

/***** Change in Institions *****/
 foreach i of numlist 1/3 {; 
regen D`i'W =F`i'.W-L.W,replace; 
regen D`i'Sreal =F`i'.Sreal-L.Sreal,replace;
};
regen LSreal=L.Sreal,replace;
/**** Use Farisss economic data in Vdem so as to get a longer time series ******/ 
#delimit;
global Xhis2  LW c.LW#c.LW  c.LlgdppcVDEM c.LW#c.LlgdppcVDEM   logIncomingTenure c.LW#c.logIncomingTenure OldorSick c.LW#c.OldorSick  LlpopVDEM  LgrowthVDEM   c.LW#c.LgrowthVDEM ; 

/* use VDem historical data to predict residuals for year >1945 */ 
global mod FE; 
foreach dep of varlist Public Private Assembly  {;
capture drop res`dep'${mod}; capture  drop hat`dep'${mod};
reghdfe `dep' $Xhis2 if year>=1946, absorb(ccode year) vce(cluster ccode)  residual(res`dep'${mod}); 
eststo `dep'HISFE ; extraout; estadd local timeT "Y";estadd local fe "Y";
predict hat`dep'${mod},xbd;
reg `dep' $Xhis2 if year>=1946,  vce(cluster ccode);  eststo `dep'HIS ; extraout; estadd local timeT "N";estadd local fe "N";
};
regen D1resPrivateFE=resPrivateFE-L.resPrivateFE,replace; 

#delimit;
global name BasicPolicyProvision2;
global Ttitle "Provision of Public Goods, Assembly, and Private Goods"; 
#delimit;
esttab PublicHIS AssemblyHIS PrivateHIS  PublicHISFE AssemblyHISFE PrivateHISFE  using "${storeresult}/${name}.tex",replace ar2 r2 se 
   title("$Ttitle\label{tab:${name}}" ) 
   stats( N Nnum yy fe timeT r2 r2_within, labels("Observations" "Number Nations" "Years" "Nation FE" "Year FE" "Fit: R2" "Fit: R2 within" )fmt(0  0 0 0 0 %8.3f  %8.3f )) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001)
  varlabel($labvar) order( )
 drop(  _cons    ) mlabels("Public" "Assembly" "Private"  "Public" "Assembly" "Private") substitute(\~ $)  addnote("Standard Errors Clustered by Country") ;
 
 

/* define lagged policy residuals */
regen LD1resPrivateFE=L.D1resPrivateFE,replace; 
regen LresPrivateFE=L.resPrivateFE,replace; 
regen LresPublicFE=L.resPublicFE,replace; 
regen LresAssemblyFE=L.resAssemblyFE,replace;   
/* define over provision as a std deviation over mean of policy residual ...*/
foreach var of varlist resPublicFE resPrivateFE resAssemblyFE {;
sum `var',detail;
regen I`var'=0 if `var'~=.,replace ; 
regen I`var' = -1 if `var'< r(mean)-r(sd) & `var'~=.,replace; 
regen I`var' = +1 if `var'> r(mean)+r(sd) & `var'~=.,replace; 
};
 label define lablab -1 "Under Provision" 0 "Expected Provision" 1 "Over Provision",  replace ;
  label values IresPublicFE IresPrivateFE IresAssemblyFE  lablab; 
capture drop _m;


/* Merge Coup Data */
merge 1:m ccode year using "COUP.dta";
sort ccode year;  
/* duplicates tag ccode year, gen(multicoup);
label var multicoup "corresponds to the number of extra events in a year"; */
 global mc "& multicoup ==0";
  global ifmc " if multicoup ==0";
 


/****************************************************/
/****************************************************/
/******* Simple Table of Observational data *********/
/****************************************************/
/****************************************************/
#delimit;
regen Wgroup=.,replace;
replace Wgroup=0 if W<=.4 & W~=.; 
replace Wgroup=1 if W>.4 & W<=.75&W~=.;
replace Wgroup=2 if W>.75&W~=.;
sum lgdppcVDEM if year>=1946,detail; 

regen RichPoor= 0 if lgdppcVDEM< 1.557934 & lgdppcVDEM~=., replace; 
regen RichPoor= 1 if lgdppcVDEM>= 1.557934 & lgdppcVDEM~=., replace; 
#delimit;
regen TenureGroup=0 if  IncomingTenure<5,replace;
regen TenureGroup=1 if  IncomingTenure>=5,replace;
sum coupChin if RichPoor==0 & TenureGroup==0 & Wgroup==0;
local m000 : display %6.2f 100*r(mean);
sum coupChin if RichPoor==0 & TenureGroup==0 & Wgroup==1;
local m001 : display %6.2f 100*r(mean);
sum coupChin if RichPoor==0 & TenureGroup==0 & Wgroup==2;
local m002 : display %6.2f 100*r(mean);
sum coupChin if RichPoor==0 & TenureGroup==0 &Wgroup~=.;
local n00 : display %6.0f r(N);

sum coupChin if RichPoor==0 & TenureGroup==1 & Wgroup==0;
local m010 : display %6.2f 100*r(mean);
sum coupChin if RichPoor==0 & TenureGroup==1 & Wgroup==1;
local m011 : display %6.2f 100*r(mean);
sum coupChin if RichPoor==0 & TenureGroup==1 & Wgroup==2;
local m012 : display %6.2f 100*r(mean);
sum coupChin if RichPoor==0 & TenureGroup==1 &Wgroup~=.;
local n01 : display %6.0f r(N);

sum coupChin if RichPoor==1 & TenureGroup==0 & Wgroup==0;
local m100 : display %6.2f 100*r(mean);
sum coupChin if RichPoor==1 & TenureGroup==0 & Wgroup==1;
local m101 : display %6.2f 100*r(mean);
sum coupChin if RichPoor==1 & TenureGroup==0 & Wgroup==2;
local m102 : display %6.2f 100*r(mean);
sum coupChin if RichPoor==1 & TenureGroup==0 &Wgroup~=.;
local n10 : display %6.0f r(N);

sum coupChin if RichPoor==1 & TenureGroup==1 & Wgroup==0;
local m110 : display %6.2f 100*r(mean);
sum coupChin if RichPoor==1 & TenureGroup==1 & Wgroup==1;
local m111 : display %6.2f 100*r(mean);
sum coupChin if RichPoor==1 & TenureGroup==1 & Wgroup==2;
local m112 : display %6.2f 100*r(mean);
sum coupChin if RichPoor==1 & TenureGroup==1 &Wgroup~=.;
local n11 : display %6.0f r(N);
sum coupChin if Wgroup==0 &RichPoor~=. & TenureGroup~=. ;
local c0 : display %6.0f r(N);
sum coupChin if Wgroup==1 &RichPoor~=. & TenureGroup~=. ;
local c1 : display %6.0f r(N);
sum coupChin if Wgroup==2 &RichPoor~=. & TenureGroup~=. ;
local c2 : display %6.0f r(N);
sum coupChin if Wgroup~=.  &RichPoor~=. & TenureGroup~=. ;
local c3 : display %6.0f r(N);

table   RichPoor TenureGroup Wgroup, stat(mean coupChin)  nformat(%6.2f); 

global header "\begin{table}[h]
\begin{center}
 \begin{threeparttable}
\def\sym#1{\ifmmode^{#1}\else\(^{#1}\)\fi}
\caption{Coalition Size, Productivity, Leader Tenure, and the Occurrence of Coups \label{tab:basicconditions}}\begin{tabular}{|cc|c|c|c|c|}
\hline &&\multicolumn{3}{c|}{W}&\\ &&Small&Medium&Large&Obs.\\ \hline" ; 
global tail " \hline \end{tabular}
\begin{tablenotes} \item Coalition sizes are W \$ \le 0.4 \$,  \$ 0.4<W \le 0.75 \$, and \$ W>0.75\$. Productivity is defined as above or below median per capita GDP. Leader tenure is divided by less that 5 years or 5 or more years. \end{tablenotes}  \end{threeparttable} \end{center} \end{table}"; 


global name basicconditions;
tempname handle ;
file open `handle' using "${storeresult}/${name}.tex", write text replace; 
file write `handle' "$header" _n;
file write `handle' "\multirow{ 2}{*}{Low Productivity} &New Leader &`m000'\%&`m001'\%&`m002'\%&`n00'\\
 &Established  Leader &`m010'\%&`m011'\%&`m012'\%&`n01'\\
 \hline
 \multirow{ 2}{*}{High Productivity} &New Leader &`m100'\%&`m101'\%&`m102'\%&`n10'\\
 &Established  Leader&`m110'\%&`m111'\%&`m112'\%&`n11' \\ \hline
  \multicolumn{2}{|c|}{Observations}&`c0'&`c1'&`c2'&`c3'\\";
file write `handle' "$tail";
file close `handle';



#delimit;
global VAR "  "Public Goods"  "Assembly"  "Private Goods" ";
global name OverUnderInstability3; 
global header "\begin{table}[htbp]\centering \begin{threeparttable}
\caption{How Under, Over or Expected Provisions of Policy Affect the Occurrence of Coups, Leader Change, and Leader Change by Irregular Means in Year t or t+1 \label{tab:$name}}
\begin{tabular}{|ll|ccc|c|}  \hline
\multicolumn{2}{|c|}{Policy Provision} &  Coup &Leader Change & Irregular LC &Observations\\ \hline  \hline "; 
global tail "\end{tabular} \begin{tablenotes} \item The table reports the proportion of nation-year observations that experience the event in year t or year t+1.  Under-provision indicates the policy is at least one standard deviation less than the expected level of policy provision. Over-provision indicates policy more than a standard deviation larger than the expected level of policy provision.  The number of observations reported is based on coup data; the number of observations for leader change data are similar but not identical.   \end{tablenotes}
  \end{threeparttable} \end{table}";
tempname handle; 
file open `handle' using "${storeresult}/${name}.tex", write text replace; 
file write `handle' "$header" _n;
local tt = 1;
 /* Cycle through each Policy Provision */
foreach var of varlist  IresPublicFE IresAssemblyFE IresPrivateFE  {; 
 global depvar : word `tt' of $VAR ; display "$depvar";
 local t=1;
foreach dep of varlist  coupChin01 LC01 LCirreg01 {;
sum `dep' if  `var'~=. $mc ;  local n`t': display %6.0fc r(N);
sum `dep' if  `var'==-1 $mc;  local n`t'm1 : display %6.0fc r(N); 
local p`t'm1: display %6.1f 100*r(mean);  
sum `dep' if  `var'==0 $mc;  local n`t'0 : display %6.0fc r(N); 
local p`t'0: display %6.1f 100*r(mean); 
sum `dep' if  `var'==1 $mc;  local n`t'1 : display %6.0fc r(N); 
local p`t'1: display %6.1f 100*r(mean); 
local t =`t'+1; };
file write `handle' " \multirow{3}{*}{${depvar} } & Under Provision &  `p1m1'\%  &
   `p2m1'\% & `p3m1'\%  &`n2m1'\\
 " _n;
 file write `handle' " & Expected Provision &  `p10'\%  &
   `p20'\% & `p30'\%  & `n20' \\
 " _n;
 file write `handle' " & Over Provision &  `p11'\%  &
   `p21'\% & `p31'\%  &`n21' \\ \hline 
 " _n; local tt=`tt'+1;
 }; 
file write `handle' "$tail";
file close `handle';
 
#delimit;
global name LOverUnderInstability3; 
global header "\begin{table}[htbp]\centering \begin{threeparttable}
\caption{How Under, Over or Expected Provisions of Policy in Year t-1 Affect the Occurrence of Coups, Leader Change, and Leader Change by Irregular Means in Year t or t+1 \label{tab:$name}}
\begin{tabular}{|ll|ccc|c|}  \hline
\multicolumn{2}{|c|}{Policy Provision} &  Coup &Leader Change & Irregular LC &Observations\\ \hline  \hline "; 
global tail "\end{tabular} \begin{tablenotes} \item The table reports the proportion of nation-year observations that experience the event in year t or year t+1.  Under-provision indicates the policy is at least one standard deviation less than the expected level of policy provision. Over-provision indicates policy more than a standard deviation larger than the expected level of policy provision.  The number of observations reported is based on coup data; the number of observations for leader change data are similar but not identical.   \end{tablenotes}
  \end{threeparttable} \end{table}";
tempname handle; 
file open `handle' using "${storeresult}/${name}.tex", write text replace; 
file write `handle' "$header" _n;
local tt = 1;
 /* Cycle through each Policy Provision */
foreach var of varlist  L.IresPublicFE L.IresAssemblyFE L.IresPrivateFE  {; 
 global depvar : word `tt' of $VAR ; display "$depvar";
 local t=1;
foreach dep of varlist  coupChin01 LC01 LCirreg01 {;
sum `dep' if  `var'~=. $mc;  local n`t': display %6.0fc r(N);
sum `dep' if  `var'==-1 $mc;  local n`t'm1 : display %6.0fc r(N); 
local p`t'm1: display %6.1f 100*r(mean);  
sum `dep' if  `var'==0 $mc;  local n`t'0 : display %6.0fc r(N); 
local p`t'0: display %6.1f 100*r(mean); 
sum `dep' if  `var'==1 $mc;  local n`t'1 : display %6.0fc r(N); 
local p`t'1: display %6.1f 100*r(mean); 
local t =`t'+1; };
file write `handle' " \multirow{3}{*}{${depvar} } & Under Provision &  `p1m1'\%  &
   `p2m1'\% & `p3m1'\%  &`n2m1'\\
 " _n;
 file write `handle' " & Expected Provision &  `p10'\%  &
   `p20'\% & `p30'\%  & `n20' \\
 " _n;
 file write `handle' " & Over Provision &  `p11'\%  &
   `p21'\% & `p31'\%  &`n21' \\ \hline 
 " _n; local tt=`tt'+1;
 }; 
file write `handle' "$tail";
file close `handle';



#delimit;
global VAR "  "Public Goods"  "Assembly"  "Private Goods" ";
global name OverUnderCoupTypes; 
global header "\begin{table}[htbp]\centering \begin{threeparttable}
\caption{How Under, Over or Expected Provisions of Policy Affect the Occurrence of Coups (P\&T), Coups (Chin), SHCoups (Chin)and CHCoups (Chin)  in Year t or t+1 \label{tab:$name}}
\begin{tabular}{|ll|cccc|c|}  \hline
\multicolumn{2}{|c|}{Policy Provision} &  Coup (P\&T) &Coups (Chin)& SHCoups (Chin)&CHCoups (Chin) &Observations\\ \hline  \hline "; 
global tail "\end{tabular} \begin{tablenotes} \item The table reports the proportion of nation-year observations that experience the event in year t or year t+1. \item Under-provision indicates the policy is at least one standard deviation less than the expected level of policy provision. Over-provision indicates policy more than a standard deviation larger than the expected level of policy provision.  The number of observations reported is based on coup data; the number of observations for revolution and leader change data are similar but not identical.   \end{tablenotes}
  \end{threeparttable} \end{table}";
tempname handle; 
file open `handle' using "${storeresult}/${name}.tex", write text replace; 
file write `handle' "$header" _n;
local tt = 1;
 /* Cycle through each Policy Provision */
foreach var of varlist  IresPublicFE IresAssemblyFE IresPrivateFE  {; 
 global depvar : word `tt' of $VAR ; display "$depvar";
 local t=1;
foreach dep of varlist  coupPT01 coupChin01 CHcoup01 SHcoup01 {;
sum `dep' if  `var'~=. $mc;  local n`t': display %6.0fc r(N);
sum `dep' if  `var'==-1 $mc;  local n`t'm1 : display %6.0fc r(N); 
local p`t'm1: display %6.1f 100*r(mean);  
sum `dep' if  `var'==0 $mc;  local n`t'0 : display %6.0fc r(N); 
local p`t'0: display %6.1f 100*r(mean); 
sum `dep' if  `var'==1 $mc;  local n`t'1 : display %6.0fc r(N); 
local p`t'1: display %6.1f 100*r(mean); 
local t =`t'+1; };
file write `handle' " \multirow{3}{*}{${depvar} } & Under Provision &  `p1m1'\%  &
   `p2m1'\% & `p3m1'\% & `p4m1'\%  &`n2m1'\\
 " _n;
 file write `handle' " & Expected Provision &  `p10'\%  &
   `p20'\% & `p30'\%  & `p40'\%& `n20' \\
 " _n;
 file write `handle' " & Over Provision &  `p11'\%  &
   `p21'\% & `p31'\% & `p41'\% &`n21' \\ \hline 
 " _n; local tt=`tt'+1;
 }; 
file write `handle' "$tail";
file close `handle';

#delimit;
global VAR "  "Public Goods"  "Assembly"  "Private Goods" ";
global name OverUnderCoupSuccess; 
global header "\begin{table}[htbp]\centering \begin{threeparttable}
\caption{How Under, Over or Expected Provisions of Policy Affect the Occurrence of Coups ,Successful Coup,  Leader Shuffling Coups (SHCoup) and Regime Change Coups (CHCoup) in Year t or t+1 (Chin et al 2021 data) \label{tab:$name}}
\begin{tabular}{|ll|cccc|c|}  \hline
\multicolumn{2}{|c|}{Policy Provision} &   Coup  &Successful Coup & SHCoups  &CHCoups &Observations\\ \hline  \hline "; 
global tail "\end{tabular} \begin{tablenotes} \item The table reports the proportion of nation-year observations that experience the event in year t or year t+1. Under-provision indicates the policy is at least one standard deviation less than the expected level of policy provision. Over-provision indicates policy more than a standard deviation larger than the expected level of policy provision.  The number of observations reported is based on coup data; the number of observations for revolution and leader change data are similar but not identical.   \end{tablenotes}
  \end{threeparttable} \end{table}";
tempname handle; 
file open `handle' using "${storeresult}/${name}.tex", write text replace; 
file write `handle' "$header" _n;
local tt = 1;
 /* Cycle through each Policy Provision */
foreach var of varlist  IresPublicFE IresAssemblyFE IresPrivateFE  {; 
 global depvar : word `tt' of $VAR ; display "$depvar";
 local t=1;
foreach dep of varlist   coupChin01 SuccessChin01 CHcoup01 SHcoup01 {;
sum `dep' if  `var'~=. $mc;  local n`t': display %6.0fc r(N);
sum `dep' if  `var'==-1 $mc;  local n`t'm1 : display %6.0fc r(N); 
local p`t'm1: display %6.1f 100*r(mean);  
sum `dep' if  `var'==0 $mc;  local n`t'0 : display %6.0fc r(N); 
local p`t'0: display %6.1f 100*r(mean); 
sum `dep' if  `var'==1 $mc;  local n`t'1 : display %6.0fc r(N); 
local p`t'1: display %6.1f 100*r(mean); 
local t =`t'+1; };
file write `handle' " \multirow{3}{*}{${depvar} } & Under Provision &  `p1m1'\%  &
   `p2m1'\% & `p3m1'\% & `p4m1'\%  &`n2m1'\\
 " _n;
 file write `handle' " & Expected Provision &  `p10'\%  &
   `p20'\% & `p30'\%  & `p40'\%& `n20' \\
 " _n;
 file write `handle' " & Over Provision &  `p11'\%  &
   `p21'\% & `p31'\% & `p41'\% &`n21' \\ \hline 
 " _n; local tt=`tt'+1;
 }; 
file write `handle' "$tail";
file close `handle';



/****************************************/
/****************************************/
/************** Occurrence of Coup Logit*/
/****************************************/
/****************************************/
#delimit;
global supersimpleRES2 LW c.LW#c.LW c.resPublicFE c.resPublicFE#c.resPublicFE c.resAssemblyFE  c.resAssemblyFE#c.resAssemblyFE c.resPrivateFE c.resPrivateFE#c.resPrivateFE c.D1resPrivateFE c.D1resPrivateFE#c.D1resPrivateFE 
c.resPrivateFE#c.D1resPrivateFE c.resPrivateFE#c.resPrivateFE#c.D1resPrivateFE c.resPrivateFE#c.D1resPrivateFE#c.D1resPrivateFE c.resPrivateFE#c.resPrivateFE#c.D1resPrivateFE#c.D1resPrivateFE
logIncomingTenure c.LW#c.logIncomingTenure OldorSick  LgrowthVDEM LlgdppcVDEM LlpopVDEM  yr yr2 yr3;

global RESMODEL $supersimpleRES2;
foreach dep of  varlist coupChin coupChin01 SuccessChin01 CHcoup01 SHcoup01    {;
logit `dep' $RESMODEL  $ifmc ,vce(cluster ccode)   ;  eststo  m`dep'; lroc, nograph;  estadd scalar roc=r(area);  estadd local nationFE "N"; estadd local yearFE "N"; count if e(sample)==1 & `dep'==1;  scalar coupN =r(N); estadd scalar Ncoup=coupN; 
extraout; };

#delimit;
global name CoupOccurence;
global Ttitle "Occurrence of Coups"; 
#delimit;
esttab mcoupChin mcoupChin01 mSuccessChin01 mCHcoup01 mSHcoup01 using "${storeresult}/${name}.tex",replace ar2 r2 se 
   title("$Ttitle\label{tab:${name}}" ) 
   stats( N Nnum yy Ncoup nationFE yearFE roc, labels("Observations" "Number Nations" "Years" "Coup-Years" "Nation FE" "Year FE" "Fit: ROC"  )fmt(0  0 0 0 0 0 %8.3f  %8.3f )) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001)
  varlabel($labvar) order( )
 drop(  _cons    ) mlabels("Coup(t)" "Coup(t or t+1)" "Success Coup"  "Coup(regime change)" "Coup(leader shuffle)") substitute(\~ $)  addnote("Standard Errors Clustered by Country") ;
/* Make Margin Plots */
#delimit;
/* varlist coupChin coupChin01 SuccessChin01 SuccessChin CHcoup01 SHcoup01*/ 
  foreach dep of  varlist coupChin  {; 
 logit `dep' $RESMODEL yr yr2 yr3   $ifmc ;
  /***********************/
local chvar resPrivateFE;  sum `chvar'  if e(sample)==1,detail; local low=r(p5); local upper=r(p95);
 local chvar2 D1resPrivateFE; sum `chvar2' if e(sample)==1,detail; local low2=r(p5); local upper2=r(p95);
local xtit "Private Goods";  local stit "Decreasing Private Goods"; 
margins, at(LW=(.1(.1)1) `chvar'=(`low',0,`upper')  `chvar2'=(`low2') ) vsquish;
global name "`dep'PriDown"; 

mplotoffset,  xdimension(LW) plotdimension(at(`chvar'))   
${cs3${bw}}   title("Effect of `xtit' on the Likelihood of `dep' " )
subtitle("`stit'" ) ytitle("Pr(`dep')") xtitle(W{sub:t-1})recast(connected) offset(.02) title("Effect of `xtit' on the Likelihood of `tit' " )  legend(order(4 "Under Provision" 5  "Anticipated Provision" 6 "Over Provision")) cap("`method'")   name(${name},replace)  graphregion(fcolor(white));
outgraph  ; 

local xtit "Private Goods";  local stit "Constant Private Goods"; 
margins, at(LW=(.1(.1)1) `chvar'=(`low',0,`upper')  `chvar2'=(0) ) vsquish;
global name "`dep'PriConst"; 
mplotoffset,  xdimension(LW) plotdimension(at(`chvar'))   
${cs3${bw}}   title("Effect of `xtit' on the Likelihood of `dep' " )
subtitle("`stit'" ) ytitle("Pr(`dep')") xtitle(W{sub:t-1})recast(connected) offset(.02) title("Effect of `xtit' on the Likelihood of `tit' " )  legend(order(4 "Under Provision" 5  "Anticipated Provision" 6 "Over Provision")) cap("`method'")   name(${name},replace)  graphregion(fcolor(white));
outgraph  ;

local xtit "Private Goods";  local stit "Increasing Private Goods"; 
margins, at(LW=(.1(.1)1) `chvar'=(`low',0,`upper')  `chvar2'=(`upper2') ) vsquish;
global name "`dep'PriUp"; 
mplotoffset,  xdimension(LW) plotdimension(at(`chvar'))   
${cs3${bw}}   title("Effect of `xtit' on the Likelihood of `dep' " )
subtitle("`stit'" ) ytitle("Pr(`dep')") xtitle(W{sub:t-1})recast(connected) offset(.02) title("Effect of `xtit' on the Likelihood of `tit' " )  legend(order(4 "Under Provision" 5  "Anticipated Provision" 6 "Over Provision")) cap("`method'")   name(${name},replace)  graphregion(fcolor(white));
outgraph  ;

 local xtit "Assembly";local chvar resAssemblyFE ; sum `chvar' if e(sample)==1,detail; local low=r(p5); local upper=r(p95); global name "`dep'Assembly";
quietly margins, at(LW=(.1(.1)1) `chvar'=(`low',0,`upper')   ) vsquish;
mplotoffset,  xdimension(LW) plotdimension(at(`chvar'))   
${cs3${bw}}  title("Effect of `xtit' on the Likelihood of `tit' " )
 ytitle("Pr(`tit')") xtitle(W{sub:t-1})recast(connected) offset(.02) title("Effect of `xtit' on the Likelihood of `tit' " )  legend(order(4 "Under Provision" 5  "Anticipated Provision" 6 "Over Provision")) cap("`method'") graphregion(fcolor(white)) name($name,replace) ;
outgraph "$name" ;
};  
/* Very Basic */ 
#delimit;

global xbasic c.LW c.LW#c.LW logIncomingTenure c.LW#c.logIncomingTenure OldorSick LgrowthVDEM c.LlgdppcVDEM c.LW#c.LlgdppcVDEM LlpopVDEM; 

global dep coupChin01; 
 logit $dep $xbasic $ifmc &year>=1946 ,vce(cluster ccode)   ;  eststo  mbasic1; lroc, nograph;  estadd scalar roc=r(area);  estadd local nationFE "N"; estadd local yearFE "N"; count if e(sample)==1 & $dep==1;  scalar coupN =r(N); estadd scalar Ncoup=coupN; regen sam=e(sample),replace;
extraout; capture drop couphat;
predict couphat, pr;
sum couphat if sam==1,detail;
regen CoupHat=(couphat>r(p50)),replace;
tab CoupHat coupChin01 if sam==1, all;
di 646/114;

 
logit $dep $xbasic i.ccode i.year $ifmc &year>=1946,vce(cluster ccode)   ;  eststo  mbasic2; lroc, nograph;  estadd scalar roc=r(area);  estadd local nationFE "Y"; estadd local yearFE "Y"; count if e(sample)==1 & $dep==1;  scalar coupN =r(N); estadd scalar Ncoup=coupN; extraout;
 
#delimit;

global name basiclogit;
global Ttitle "Winninc Coalition Size, Productivity and Leader Tenure and the Occurrence of Coups (t or t+1)"; 
#delimit;
esttab mbasic1 mbasic2 using "${storeresult}/${name}.tex",replace ar2 r2 se 
   title("$Ttitle\label{tab:${name}}" ) 
   stats( N Nnum yy Ncoup nationFE yearFE roc, labels("Observations" "Number Nations" "Years" "Coup-Years" "Nation FE" "Year FE" "Fit: ROC"  )fmt(0  0 0 0 0 0 %8.3f  %8.3f )) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001)
  varlabel($labvar) order( )
 drop(  _cons  *.year *.ccode  ) mlabels("No Fixed Effects" "Fixed Effects") substitute(\~ $)  addnote("Standard Errors Clustered by Country") ; 

/**********************************************/
/**********************************************/
/***** Explore Mechanisms *********************/
/**********************************************/
/**********************************************/
/**** Throbit ******/

#delimit;
capture program drop throbitSIM;
program define throbitSIM; 
args lnf b1 b2 ; tempvar areat0 area0t area00;
qui gen double `areat0' = normprob(`b1')*normprob(-`b2');
qui gen double `area0t' = normprob((`b2'))*normprob(-(`b1'));
qui gen double `area00' = normprob(-(`b2'))*normprob(-(`b1'));
quietly replace `lnf'=ln(`areat0') if $y1 ==1 ;
quietly replace `lnf'=ln(`area0t') if $y2 ==1 ;
quietly replace `lnf'=ln(`area00') if $y ==0; 
quietly replace `lnf'=ln(1-`area00'-`area0t'-`areat0') if ($y ==1 & $y1 ~=1 & $y2 ~=1);
quietly replace `lnf'=ln(1-`area00') if ($y ==1 & $y1 ~=1 & $y2 ~=1); 
end;

#delimit;
global dep coupChin; 
regen coupunder=0,replace;
regen coupunder=1 if $dep==1 &  resPrivateFE<-.07 & resPrivateFE~=.& D1resPrivateFE~=.,replace ;
regen coupover=0,replace;
regen coupover=1 if $dep==1 &  resPrivateFE>.07 & resPrivateFE~=.& D1resPrivateFE>.02 & D1resPrivateFE~=.,replace ;

tab coupunder coupover if coupChin==1;
global y $dep; global y1 coupunder; global y2 coupover;

/**model specifications **/ 
global x1 c.LW c.LW#c.LW   c.resPrivateFE c.D1resPrivateFE c.resPublicFE  c.resAssemblyFE logIncomingTenure c.LW#c.logIncomingTenure OldorSick LgrowthVDEM c.LlgdppcVDEM c.LW#c.LlgdppcVDEM LlpopVDEM  ;
global x2 c.LW c.LW#c.LW c.resPrivateFE c.D1resPrivateFE c.resPublicFE  c.resAssemblyFE logIncomingTenure c.LW#c.logIncomingTenure OldorSick   LgrowthVDEM c.LlgdppcVDEM c.LW#c.LlgdppcVDEM LlpopVDEM  ; 

global x1a c.LW c.LW#c.LW   c.resPrivateFE c.D1resPrivateFE c.resPrivateFE#c.D1resPrivateFE c.resPublicFE  c.resAssemblyFE logIncomingTenure c.LW#c.logIncomingTenure OldorSick LgrowthVDEM c.LlgdppcVDEM c.LW#c.LlgdppcVDEM LlpopVDEM  ;
global x2a c.LW c.LW#c.LW c.resPrivateFE c.D1resPrivateFE c.resPrivateFE#c.D1resPrivateFE c.resPublicFE  c.resAssemblyFE logIncomingTenure c.LW#c.logIncomingTenure OldorSick   LgrowthVDEM c.LlgdppcVDEM c.LW#c.LlgdppcVDEM LlpopVDEM  ; 

#delimit;

#delimit;
global x4a c.LW c.LW#c.LW c.resPrivateFE c.D1resPrivateFE c.resPrivateFE#c.D1resPrivateFE LDmilitaryGDP c.resPublicFE  c.resAssemblyFE logIncomingTenure c.LW#c.logIncomingTenure OldorSick   LgrowthVDEM c.LlgdppcVDEM c.LW#c.LlgdppcVDEM LlpopVDEM  ; 
#delimit;
/**model specifications **/ 
global x1 c.LW c.LW#c.LW LSreal c.resPrivateFE c.D1resPrivateFE c.resPublicFE c.resAssemblyFE   logIncomingTenure c.LW#c.logIncomingTenure OldorSick LgrowthVDEM c.LlgdppcVDEM c.LW#c.LlgdppcVDEM LlpopVDEM  ;
global x2 c.LW c.LW#c.LW  LSreal c.resPrivateFE c.D1resPrivateFE c.resPublicFE  c.resAssemblyFE logIncomingTenure c.LW#c.logIncomingTenure OldorSick   LgrowthVDEM c.LlgdppcVDEM c.LW#c.LlgdppcVDEM LlpopVDEM  ; 

global x1a c.LW c.LW#c.LW LSreal  c.resPrivateFE c.D1resPrivateFE c.resPrivateFE#c.D1resPrivateFE c.resPublicFE  c.resAssemblyFE logIncomingTenure c.LW#c.logIncomingTenure OldorSick LgrowthVDEM c.LlgdppcVDEM c.LW#c.LlgdppcVDEM LlpopVDEM  ;
global x2a c.LW c.LW#c.LW LSreal c.resPrivateFE c.D1resPrivateFE c.resPrivateFE#c.D1resPrivateFE c.resPublicFE c.resAssemblyFE logIncomingTenure c.LW#c.logIncomingTenure OldorSick   LgrowthVDEM c.LlgdppcVDEM c.LW#c.LlgdppcVDEM LlpopVDEM  ; 

logit $dep  $x1 $ifmc ; regen sam=e(sample)==1,replace; 
#delimit;

ml model lf throbitSIM ( $x1a ) ($x2a  )  $ifmc  , vce(cluster ccode);
ml maximize, difficult ; 
eststo throb1a; extraout;estadd local nationFE "N"; estadd local yearFE "N"; count if e(sample)==1 & $y==1;  scalar coupN =r(N); estadd scalar Ncoup=coupN; 

#delimit;
ml model lf throbitSIM ( $x1 ) ($x2  )  $ifmc  , vce(cluster ccode);
ml maximize, difficult ; 
eststo throb1; extraout;estadd local nationFE "N"; estadd local yearFE "N"; count if e(sample)==1 & $y==1;  scalar coupN =r(N); estadd scalar Ncoup=coupN; 
#delimit;
capture drop throbhat1 throbhat2;
predict throbhat1, equation(eq1);predict throbhat2, equation(eq2);
regen throbhat1p=normal(throbhat1),replace;regen throbhat2p=normal(throbhat2),replace;





  
 

  

 /****** For FE model restrict the sample to nations with at kleast three coups ********/
 /* Also work only with nations that have coups */ 
#delimit;
capture by ccode: egen maxcoup=max(coupChin); 
capture by ccode: egen sumcoup=sum(coupChin) if sam==1; 
capture bysort year: egen maxcoupyear=max(coupChin) if sam==1;
sort ccode year;
#delimit;
ml model lf throbitSIM ( $x1 i.ccode i.year) ($x2 i.ccode i.year)  $ifmc &sumcoup>2  , vce(cluster ccode);
ml maximize, difficult ; 
eststo throb1fe; extraout;estadd local nationFE "Y"; estadd local yearFE "Y"; count if e(sample)==1 & $y==1;  scalar coupN =r(N); estadd scalar Ncoup=coupN;
#delimit;

#delimit;
global name overunderFE; global Ttitle "Two Mechanisms for Coups: Under-Provision and Over-Provision Coups (Analysis with nation and year fixed effects is restricted to nations experiencing at least 3 coups.)";
 esttab throb1fe  using "${storeresult}/${name}.tex",replace ar2 r2 se title("$Ttitle\label{tab:${name}}" ) stats( N Nnum yy Ncoup nationFE yearFE  , labels("Observations" "Number Nations" "Years" "Coup-years" "Nation FE" "Year FE"  "Fit: R2"  )fmt(0 0 0 0 0 0 %8.3f 0 %8.3f )) star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar) order(   ) drop(  _cons   *.ccode *.year ) mlabels("Under-provision" "Over-provision"   ) substitute(\~ $)  addnote("Standard Errors Clustered by Country") unstack;

#delimit;
global name overunderMix; global Ttitle "Two Mechanisms for Coups: Under-Provision and Over-Provision Coups (Analysis of the second model with nation and year fixed effects is restricted to nations that experience at least 3 coups.)";
 esttab throb1 throb1fe  using "${storeresult}/${name}.tex",replace ar2 r2 se title("$Ttitle\label{tab:${name}}" ) stats( N Nnum yy Ncoup nationFE yearFE  , labels("Observations" "Number Nations" "Years" "Nation-years experiencing coup" "Nation FE" "Year FE"  "Fit: R2"  )fmt(0 0 0 0 0 0 %8.3f 0 %8.3f )) star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar) order(   ) drop(  _cons   *.ccode *.year ) mlabels("Under-provision" "Over-provision"   ) substitute(\~ $)  addnote("Standard Errors Clustered by Country") unstack;

**# Bookmark #1
 
 #delimit;
 local i=1;
 levelsof year if sam==1 & maxcoupyear==1& sumcoup>2, local(levels) ;
foreach l of local levels {;
constraint define `i' [eq1]:`l'.year=[eq2]:`l'.year;
local i =`i'+1; di "`i'"; };
 levelsof ccode if sam==1 & maxcoupyear==1& sumcoup>2 , local(levels) ;
foreach l of local levels {;
constraint define `i' [eq1]:`l'.ccode=[eq2]:`l'.ccode;
local i =`i'+1; di "`i'";
}; 
 
 
 

#delimit;
ml model lf throbitSIM ( $x1 i.ccode i.year) ($x2 i.ccode i.year)  $ifmc &sumcoup>2  , vce(cluster ccode) constraint( 2/76 78/100 101/129);
ml maximize, difficult ; eststo throb1samefe; extraout;estadd local nationFE "Y"; estadd local yearFE "Y"; count if e(sample)==1 & $y==1;  scalar coupN =r(N); estadd scalar Ncoup=coupN;

#delimit;
global name overunderSameFE; global Ttitle "Two Mechanisms for Coups: Under-Provision and Over-Provision Coups (Fixed effects for nation and year with the restriction that the fixed effects are the same for each mechanism.)";
 esttab  throb1samefe  using "${storeresult}/${name}.tex",replace ar2 r2 se title("$Ttitle\label{tab:${name}}" ) stats( N Nnum yy Ncoup nationFE yearFE  , labels("Observations" "Number Nations" "Years" "Nation-years experiencing coup" "Nation FE" "Year FE"  "Fit: R2"  )fmt(0 0 0 0 0 0 %8.3f 0 %8.3f )) star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar) order(   ) drop(  _cons   *.ccode *.year ) mlabels("Under-provision" "Over-provision"   ) substitute(\~ $)  addnote("Standard Errors Clustered by Country") unstack;



 
#delimit;
ml model lf throbitSIM ( $x1  ) ($x1  ) $ifmc , vce(cluster ccode);
ml maximize, difficult ; 
 
 
 
 
/****** margins plot ********/
/* across coalition size */ 
#delimit;
/***********************/
local chvar resPrivateFE;  sum `chvar'  if e(sample)==1,detail; local low=r(p5); local upper=r(p95);
 local chvar2 D1resPrivateFE; sum `chvar2' if e(sample)==1,detail; local low2=r(p5); local upper2=r(p95);
local dd pridown1; 
margins, at(LW=(.1(.1)1) `chvar'=(`low',0,`upper')  `chvar2'=(`low2') )  predict(equation(eq1)) vsquish  saving(${storeresult}/file`dd', replace);
local dd pridown2; 
margins, at(LW=(.1(.1)1) `chvar'=(`low',0,`upper')  `chvar2'=(`low2') ) predict(equation(eq2)) vsquish  saving(${storeresult}/file`dd', replace);
local dd priconst1; 
margins, at(LW=(.1(.1)1) `chvar'=(`low',0,`upper')  `chvar2'=(0) ) predict(equation(eq1)) vsquish  saving(${storeresult}/file`dd', replace);
local dd priconst2; 
margins, at(LW=(.1(.1)1) `chvar'=(`low',0,`upper')  `chvar2'=(0) ) predict(equation(eq2)) vsquish  saving(${storeresult}/file`dd', replace);
local dd priup1; 
margins, at(LW=(.1(.1)1) `chvar'=(`low',0,`upper')  `chvar2'=(`upper2') ) predict(equation(eq1)) vsquish  saving(${storeresult}/file`dd', replace);
local dd priup2; 
margins, at(LW=(.1(.1)1) `chvar'=(`low',0,`upper')  `chvar2'=(`upper2') ) predict(equation(eq2)) vsquish  saving(${storeresult}/file`dd', replace);

local chvar resAssemblyFE;  sum `chvar'  if e(sample)==1,detail; local low=r(p5); local upper=r(p95);
local dd ass1; 
margins, at(LW=(.1(.1)1) `chvar'=(`low',0,`upper')   ) predict(equation(eq1)) vsquish  saving(${storeresult}/file`dd', replace);
local dd ass2; 
margins, at(LW=(.1(.1)1) `chvar'=(`low',0,`upper')   ) predict(equation(eq2)) vsquish  saving(${storeresult}/file`dd', replace);


capture frame create temp; 

#delimit;
frame change temp; 
global flist filepridown1 filepriconst1 filepriup1 fileass1 filepridown2 filepriconst2 filepriup2 fileass2; 
 
foreach ff of  global flist {;
use ${storeresult}/`ff', clear; 
replace _margin=normal(_margin); replace _ci_lb=normal( _ci_lb); replace _ci_ub=normal( _ci_ub); save ${storeresult}/`ff', replace;}; frame change default;

#delimit;
global name "Eq12pridown1";
 combomarginsplot "${storeresult}/filepridown1"  ,  name("$name" , replace) title(" UnderProvision Coups") subtitle("Decreasing Private Goods" ) ${cs3${bw}} ytitle("Pr(coup1)" )  xtitle(W{sub:t-1})  recast(connected) offset(.02)       legend(order(4 "Under Provision" 5  "Anticipated Provision" 6 "Over Provision")) cap("`method'")     graphregion(fcolor(white));outgraph "$name" ;

#delimit;
global name "Eq12priconst1";
 combomarginsplot "${storeresult}/filepriconst1"  ,  name("$name" , replace) title(" UnderProvision Coups") subtitle("Constant Private Goods" ) ${cs3${bw}} ytitle("Pr(coup1)" )  xtitle(W{sub:t-1})  recast(connected) offset(.02)     legend(order(4 "Under Provision" 5  "Anticipated Provision" 6 "Over Provision")) cap("`method'")     graphregion(fcolor(white)); outgraph "$name" ;
 
 #delimit;
global name "Eq12priup1";
 combomarginsplot "${storeresult}/filepriup1"  ,  name("$name" , replace) title(" UnderProvision Coups") subtitle("Increasing Private Goods" ) ${cs3${bw}} ytitle("Pr(coup1)" )  xtitle(W{sub:t-1})  recast(connected) offset(.02)      legend(order(4 "Under Provision" 5  "Anticipated Provision" 6 "Over Provision")) cap("`method'")     graphregion(fcolor(white)); outgraph "$name" ;
 
 #delimit;
global name "Eq12ass1";
 combomarginsplot "${storeresult}/fileass1"  ,  name("$name" , replace) title(" UnderProvision Coups") subtitle("Assembly" ) ${cs3${bw}} ytitle("Pr(coup1)" )  xtitle(W{sub:t-1})  recast(connected) offset(.02)    legend(order(4 "Under Provision" 5  "Anticipated Provision" 6 "Over Provision")) cap("`method'")     graphregion(fcolor(white)); outgraph "$name" ;

 #delimit;
global name "Eq12pridown2";
 combomarginsplot "${storeresult}/filepridown2"  ,  name("$name" , replace) title(" OverProvision Coups") subtitle("Decreasing Private Goods" ) ${cs3${bw}} ytitle("Pr(coup1)" )  xtitle(W{sub:t-1})  recast(connected) offset(.02)        legend(order(4 "Under Provision" 5  "Anticipated Provision" 6 "Over Provision")) cap("`method'")     graphregion(fcolor(white));outgraph "$name" ;

#delimit;
global name "Eq12priconst2";
 combomarginsplot "${storeresult}/filepriconst2"  ,  name("$name" , replace) title(" OverProvision Coups") subtitle("Constant Private Goods" ) ${cs3${bw}} ytitle("Pr(coup1)" )  xtitle(W{sub:t-1})  recast(connected) offset(.02)    legend(order(4 "Under Provision" 5  "Anticipated Provision" 6 "Over Provision")) cap("`method'")     graphregion(fcolor(white)); outgraph "$name" ;
 
 #delimit;
global name "Eq12priup2";
 combomarginsplot "${storeresult}/filepriup2"  ,  name("$name" , replace) title(" OverProvision Coups") subtitle("Increasing Private Goods" ) ${cs3${bw}} ytitle("Pr(coup1)" )  xtitle(W{sub:t-1})  recast(connected) offset(.02)    legend(order(4 "Under Provision" 5  "Anticipated Provision" 6 "Over Provision")) cap("`method'")     graphregion(fcolor(white)); outgraph "$name" ;
 
 #delimit;
global name "Eq12ass2";
 combomarginsplot "${storeresult}/fileass2"  ,  name("$name" , replace) title(" OverProvision Coups") subtitle("Assembly" ) ${cs3${bw}} ytitle("Pr(coup1)" )  xtitle(W{sub:t-1})  recast(connected) offset(.02)       legend(order(4 "Under Provision" 5  "Anticipated Provision" 6 "Over Provision")) cap("`method'")     graphregion(fcolor(white));  outgraph "$name" ;
 
/*** Margins plot for private goods at LW=.5 ******/
#delimit;
sum D1resPrivateFE if sam==1,detail; local low2=r(p5); local upper2=r(p95);
local ddd pri; 
margins, at(LW=(.5) resPrivateFE=(-.12(.03).12)  D1resPrivateFE=(`low2',0,`upper2') ) predict(equation(eq1)) vsquish  saving(${storeresult}/file`ddd'1, replace);
margins, at(LW=(.5) resPrivateFE=(-.12(.03).12)  D1resPrivateFE=(`low2',0,`upper2') ) predict(equation(eq2)) vsquish  saving(${storeresult}/file`ddd'2, replace);

#delimit;
frame change temp; 
global flist filepri1 filepri2; 
 foreach ff of  global flist {;
use ${storeresult}/`ff', clear; 
replace _margin=normal(_margin); replace _ci_lb=normal( _ci_lb); replace _ci_ub=normal( _ci_ub); save ${storeresult}/`ff', replace;}; frame change default;
#delimit;
global name "underPri1"; 
combomarginsplot "${storeresult}/filepri1"  ,  name("$name" , replace) title(" UnderProvision Coups") subtitle("Private Goods" ) ${cs3${bw}} ytitle("Pr(coup1)" )  xtitle("Private Goods (deviation from expectations)")  recast(connected) offset(.002)       legend(order(4 "Decreasing Provision" 5  "Constant Provision" 6 "Increasing Provision")) cap("`method'")     graphregion(fcolor(white));outgraph "$name" ;

global name "OverPri2"; 
combomarginsplot "${storeresult}/filepri2"  ,  name("$name" , replace) title(" OverProvision Coups") subtitle("Private Goods" ) ${cs3${bw}} ytitle("Pr(coup1)" )  xtitle("Private Goods (deviation from expectations)")  recast(connected) offset(.002)      legend(order(4 "Decreasing Provision" 5  "Constant Provision" 6 "Increasing Provision")) cap("`method'")     graphregion(fcolor(white));outgraph "$name" ;

#delimit;
/****** Coups with and without outside help ******/
regen coupChinNoO= coupChin,replace;
replace coupChinNoO=0 if OutsideHelp==1;
regen coupChinOut= coupChin,replace;
replace coupChinOut=0 if OutsideHelp==0;
regen coupunderNoO=coupunder,replace;
replace coupunderNoO=0 if OutsideHelp==1;
regen coupoverNoO=coupover,replace;
replace coupoverNoO=0 if OutsideHelp==1;
regen coupunderOut=coupunder,replace;
replace coupunderOut=0 if OutsideHelp==0;
regen coupoverOut=coupover,replace;
replace coupoverOut=0 if OutsideHelp==0;

#delimit;
global y coupChinNoO; global y1 coupunderNoO; global y2 coupoverNoO;
ml model lf throbitSIM ( $x1 ) ($x2 )  $ifmc  , vce(cluster ccode);
ml maximize, difficult ; 
eststo mchinNoO;extraout;estadd local nationFE "N"; estadd local yearFE "N"; count if e(sample)==1 & $y==1;  scalar coupN =r(N); estadd scalar Ncoup=coupN;

#delimit;
global y coupChinOut; global y1 coupunderOut; global y2 coupoverOut;
ml model lf throbitSIM ( $x1 ) ($x2 )  $ifmc  , vce(cluster ccode);
ml maximize, difficult ; 
eststo mchinOut;extraout;estadd local nationFE "N"; estadd local yearFE "N"; count if e(sample)==1 & $y==1;  scalar coupN =r(N); estadd scalar Ncoup=coupN;


#delimit;
global name overunderNoFEOut; global Ttitle "Two Mechanisms for Coups: Under-Provision and Over-Provision Coups: With and Without Outside Help";
 esttab mchinNoO mchinOut using "${storeresult}/${name}.tex",replace ar2 r2 se title("$Ttitle\label{tab:${name}}" ) stats( N Nnum yy Ncoup nationFE yearFE  , labels("Observations" "Number Nations" "Years" "Coup-years" "Nation FE" "Year FE"  "Fit: R2"  )fmt(0 0 0 0 0 0 %8.3f 0 %8.3f )) star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar) order(   ) drop(  _cons    ) mlabels("Under-provision" "Over-provision"   ) substitute(\~ $)  addnote("Standard Errors Clustered by Country") unstack;


/***** Robustness tests: Powell and Thyne and CSPS coup data *****/ 
 #delimit;
 
 regen coupAll=coupChin,replace;
 replace coupAll=1 if AnyCoupPT==1 |coupCSPS==1; 
 /***PT coups ****/ 
global dep AnyCoupPT; 
regen coupunderPT =0,replace;
regen coupunderPT=1 if $dep==1 &  resPrivateFE<-.05 & resPrivateFE~=.& D1resPrivateFE~=.,replace ; 
regen coupoverPT=0,replace;
regen coupoverPT=1 if $dep==1 &  resPrivateFE>.05 & resPrivateFE~=.& D1resPrivateFE>.02 & D1resPrivateFE~=.,replace ;
global y coupAll; global y1 coupunder ; global y2 coupover ;
#delimit;

global y AnyCoupPT; global y1 coupunder  ; global y2 coupover  ;

global y coupChin; global y1 coupunder  ; global y2 coupover  ;
#delimit;
 
global xsim c.LW c.LW#c.LW  c.resPrivateFE c.D1resPrivateFE  c.logIncomingTenure ;
 
#delimit;
regen same=0,replace; 
replace same =1 if AnyCoupPT==coupChin ;
gen extraNo=(same==0 & AnyCoupPT==0);
gen extraYes=(same==0 & AnyCoupPT==1);
  
ml model lf throbitSIM ( $x1  ) ($x2   )  if multicoup==0&(same==1 |extraYes==1|extraNo==1) , vce(cluster ccode); 
ml maximize,   difficult ; 

eststo mPT; extraout;estadd local nationFE "N"; estadd local yearFE "N"; count if e(sample)==1 & $y==1;  scalar coupN =r(N); estadd scalar Ncoup=coupN; 


/***CSPS coups ****/ 
#delimit;
global dep coupCSPS ;

#delimit;
global y coupCSPS; global y1 coupunder; global y2 coupover;
#delimit;
regen same=0,replace; 
replace same =1 if coupCSPS==coupChin ;
regen extraNo=(same==0 & coupCSPS==0),replace;
regen extraYes=(same==0 & coupCSPS==1),replace;
ml model lf throbitSIM ( $x1 ) ($x2  )  if multicoup==0&(same==1 |extraYes==1|extraNo==1) , vce(cluster ccode) ;
ml check;
ml search, repeat(20);
ml maximize,  difficult ; 
eststo mCSPS; extraout;estadd local nationFE "N"; estadd local yearFE "N"; count if e(sample)==1 & $y==1;  scalar coupN =r(N); estadd scalar Ncoup=coupN; 
#delimit;





 #delimit;
global name PTCSPS; global Ttitle "Two Mechanisms for Coups: Under-Provision and Over-Provision Coups: Data from \cite{powell2011global} and \cite{CSPS}";
 esttab mPT mCSPS using "${storeresult}/${name}.tex",replace ar2 r2 se title("$Ttitle\label{tab:${name}}" ) stats( N Nnum yy Ncoup nationFE yearFE  , labels("Observations" "Number Nations" "Years" "Coup-years" "Nation FE" "Year FE"  "Fit: R2"  )fmt(0 0 0 0 0 0 %8.3f 0 %8.3f )) star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar) order(   ) drop(  _cons    ) mlabels("Under-provision" "Over-provision"   ) substitute(\~ $)  addnote("Standard Errors Clustered by Country") unstack;

 
/*****************************************************/
/*****************************************************/
/* Implications of Coup Risk */
/*****************************************************/
/*****************************************************/
/*** Likelihood of Coup and likelihood of Change in W*/ 
regen AnyD2W=(abs(D2W)>.03),replace;
logit AnyD2W LW throbhat1 throbhat2;
logit AnyD2W c.LW##c.LW throbhat1p throbhat2p yr yr2 yr3, vce(cluster ccode) ; eststo mAnyD2W1;extraout; lroc, nograph;  estadd scalar roc=r(area);  estadd local nationFE "N"; estadd local yearFE "N"; 
logit AnyD2W c.LW##c.LW throbhat1p throbhat2p coupChin yr yr2 yr3, vce(cluster ccode) ; eststo mAnyD2W2;extraout; lroc, nograph;  estadd scalar roc=r(area);  estadd local nationFE "N"; estadd local yearFE "N"; 
logit AnyD2W c.LW##c.LW throbhat1p throbhat2p yr yr2 yr3   if LC01==0 , vce(cluster ccode) ; eststo mAnyD2W3;extraout; lroc, nograph;  estadd scalar roc=r(area);  estadd local nationFE "N"; estadd local yearFE "N"; 

logit AnyD2W c.LW##c.LW throbhat1p throbhat2p i.ccode yr yr2 yr3, vce(cluster ccode) ; eststo mAnyD2W1fe;extraout; lroc, nograph;  estadd scalar roc=r(area);  estadd local nationFE "Y"; estadd local yearFE "N"; 
logit AnyD2W c.LW##c.LW throbhat1p throbhat2p coupChin i.ccode yr yr2 yr3, vce(cluster ccode) ; eststo mAnyD2W2fe;extraout; lroc, nograph;  estadd scalar roc=r(area);  estadd local nationFE "Y"; estadd local yearFE "N"; 
logit AnyD2W c.LW##c.LW throbhat1p throbhat2p i.ccode yr yr2 yr3 if LC01==0 , vce(cluster ccode) ; eststo mAnyD2W3fe;extraout; lroc, nograph;  estadd scalar roc=r(area);  estadd local nationFE "Y"; estadd local yearFE "N"; 

global name PredAnyD2W;
global Ttitle "Coup Risks and the Occurrence of Institution Change: \~ |\Delta W | > 0.03\~ "; 
#delimit;
esttab mAnyD2W1 mAnyD2W2 mAnyD2W3 mAnyD2W1fe mAnyD2W2fe mAnyD2W3fe using "${storeresult}/${name}.tex",replace ar2 r2 se 
   title("$Ttitle\label{tab:${name}}" ) 
   stats( N Nnum yy nationFE yearFE roc, labels("Observations" "Number Nations" "Years" "Nation FE" "Year FE" "Fit: ROC"  )fmt(0  0 0 0 0 %8.3f  %8.3f )) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001)
  varlabel($labvar coupChin "Coup"  throbhat1p "\~ \widehat{Coup}_{under} \~"  throbhat2p "\~ \widehat{Coup}_{over} \~" ) order( )
 drop(  _cons  *.ccode yr*  ) mlabels("Risks" "Risks/Occurrence" "Absent LC" "Risks" "Risks/Occurrence" "Absent LC") substitute(\~ $)  addnote("Standard Errors Clustered by Country") ;

/**** Does likelihood of Coup predict D2W****/ 
#delimit;
global cond "if abs(D2W)> 0.03 " ; 
twoway (  scatter D2W throbhat1 $cond) (  qfit D2W throbhat1 $cond ),name(underscatter,replace) title("Predicted Likelihood of UnderProvision Coup");

twoway (  scatter D2W throbhat2 $cond ) (  qfit D2W throbhat2 $cond ),name(overscatter,replace) title("Predicted Likelihood of OverProvision Coup");


global cond "if abs(D2W)> 0.03 & LC01==0 " ; twoway (  scatter D2W throbhat1 $cond) (  qfit D2W throbhat1 $cond ),name(underscatterNoLC,replace) title("Predicted Likelihood of UnderProvision Coup");

twoway (  scatter D2W throbhat2 $cond ) (  qfit D2W throbhat2 $cond ),name(overscatterNoLC,replace) title("Predicted Likelihood of OverProvision Coup");




#delimit;
reg D2W c.LW  throbhat1p throbhat2p , vce(cluster ccode);eststo m1D2W; 
extraout; estadd scalar rfit=e(r2);  estadd local nationFE "N"; estadd local yearFE "N"; 
reghdfe D2W c.LW  throbhat1p throbhat2p ,a(ccode year) vce(cluster ccode);eststo m2D2W; 
extraout; estadd scalar rfit=e(r2) ; estadd local nationFE "Y"; estadd local yearFE "Y"; 
#delimit;

reghdfe D2W c.LW  throbhat1p throbhat2p  if abs(D2W>.03),a(ccode year) vce(cluster ccode);eststo m3D2W;extraout; estadd scalar rfit=e(r2);  estadd local nationFE "Y"; estadd local yearFE "Y"; 

#delimit;
reghdfe D2W c.LW throbhat1p throbhat2p  if abs(D2W>.03) & LC01==0,a(ccode year) vce(cluster ccode);eststo m4D2W;extraout; estadd scalar rfit=e(r2);  estadd local nationFE "Y"; estadd local yearFE "Y"; 


#delimit;
hetregress D2W c.LW  throbhat1p throbhat2p ,het(throbhat1p throbhat2p) vce(cluster ccode); regen sam2=e(sample),replace; capture drop hattemp; predict hattemp ; regen restemp=D2W-hattemp,replace; 
sum restemp; scalar r1=r(Var);  di "var " r1;
sum D2W if sam2==1; scalar r2=r(Var); scalar r3= (r2-r1)/r2; drop hattemp sam2 restemp; 
hetregress D2W c.LW  throbhat1p throbhat2p   ,het(throbhat1p throbhat2p) vce(cluster ccode);eststo m5D2W;extraout;estadd scalar rfit=r3;  estadd local nationFE "N"; estadd local yearFE "N"; 

#delimit;
hetregress D2W c.LW  throbhat1p throbhat2p i.ccode i.year ,het(throbhat1p throbhat2p) vce(cluster ccode);
regen sam2=e(sample),replace; capture drop hattemp; predict hattemp ; regen restemp=D2W-hattemp,replace; 
sum restemp; scalar r1=r(Var);  di "var " r1;
sum D2W if sam2==1; scalar r2=r(Var);
scalar r3= (r2-r1)/r2; drop hattemp sam2 restemp; 
hetregress D2W c.LW  throbhat1p throbhat2p i.ccode i.year ,het(throbhat1p throbhat2p) vce(cluster ccode);eststo m6D2W;extraout; estadd scalar rfit=r3;  estadd local nationFE "Y"; estadd local yearFE "Y"; 


global name regD2W;  global Ttitle "How the Likelihood of Coup by Each Mechanism Affects Institution Change: \~ \Delta W= W_{t+2}-W_{t-1} \~ ";
esttab m1D2W m2D2W m3D2W  m5D2W m6D2W using "${storeresult}/${name}.tex",replace ar2 r2 se  title("$Ttitle \label{tab:${name}}" ) stats( N Nnum yy nationFE yearFE rfit r2_within, labels("Observations" "Number Nations" "Years" "Nation FE" "Year FE" "Fit: R2" "Fit: R2 within" )fmt(0  0 0 0 0 %8.3f  %8.3f )) star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar coupChin "Coup"  throbhat1p "\~ \widehat{Coup}_{under} \~"  throbhat2p "\~ \widehat{Coup}_{over} \~" ) order( )
 drop(  _cons  *.ccode *.year  ) mlabels("All Obs." "All Obs." "\~ |\Delta W|>.03 \~" "Heteroskedastic" "Heteroskedastic") substitute(\~ $)  addnote("Standard Errors Clustered by Country") ;

 
/********** D2W: and coups ********/  
#delimit;
reg D2W c.LW  throbhat1p throbhat2p coupChin01, vce(cluster ccode);eststo m1D2Wc; 
extraout; estadd scalar rfit=e(r2);  estadd local nationFE "N"; estadd local yearFE "N"; 
reghdfe D2W c.LW  throbhat1p throbhat2p coupChin01,a(ccode year) vce(cluster ccode);eststo m2D2Wc; 
extraout; estadd scalar rfit=e(r2) ; estadd local nationFE "Y"; estadd local yearFE "Y"; 
 
reg D2W c.LW  throbhat1p throbhat2p coupChin01 if LC01==0, vce(cluster ccode);eststo m1D2Wnolc; 
extraout; estadd scalar rfit=e(r2);  estadd local nationFE "N"; estadd local yearFE "N"; 

reg D2W c.LW  throbhat1p throbhat2p coupChin01 if LC01==1, vce(cluster ccode);eststo m1D2Wlc; 
extraout; estadd scalar rfit=e(r2);  estadd local nationFE "N"; estadd local yearFE "N"; 

global name regD2Wextra;  global Ttitle "How the Likelihood of Coup by Each Mechanism Affects Institution Change: \~ \Delta W= W_{t+2}-W_{t-1} \~ ";
esttab m1D2Wc m2D2Wc m1D2Wnolc m1D2Wlc using "${storeresult}/${name}.tex",replace ar2 r2 se  title("$Ttitle \label{tab:${name}}" ) stats( N Nnum yy nationFE yearFE rfit r2_within, labels("Observations" "Number Nations" "Years" "Nation FE" "Year FE" "Fit: R2" "Fit: R2 within" )fmt(0  0 0 0 0 %8.3f  %8.3f )) star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar coupChin01 "Coup"  throbhat1p "\~ \widehat{Coup}_{under} \~"  throbhat2p "\~ \widehat{Coup}_{over} \~" ) order( )
 drop(  _cons   ) mlabels("All Obs." "Fixed Effects" "Absent LC" "With LC") substitute(\~ $)  addnote("Standard Errors Clustered by Country") ;

 
 
  #delimit;
  capture drop resd2w;capture drop hatd2wfe;
reghdfe D2W c.LW  throbhat1p throbhat2p, absorb(ccode year) vce(cluster ccode)  residual(resd2w);capture drop hatd2w; predict hatd2wfe, xbd;
#delimit;
reg D2W c.LW  throbhat1p throbhat2p ,  vce(cluster ccode)  ;capture drop hatd2wnofe;predict hatd2wnofe, xb;
twoway ( scatter hatd2wnofe D2W if abs(D2W)>.03) ( lfitci hatd2wnofe D2W ),name(dd,replace);
global name scatterd2wpredfe;
twoway ( scatter hatd2wfe D2W if abs(D2W)>.01, symbol(Oh) ) ( lfitci hatd2wfe D2W ),name("$name",replace) ytitle("Predicted Change in W") xtitle("Change in W: {&Delta}W=W{sub:t+2}-W{sub:t-1}") title("Predicted vs Actual Change: {&Delta}W=W{sub:t+2}-W{sub:t-1}") legend(off) xlabel(-.5 -.4 -.3 -.2 -.1 0 .1 .2  .3 .4 .5 .6) yline(0) xline(0) graphregion(fcolor(white)); 
outgraph;




  #delimit;
regen ID2W=0 if D2W<0 & D2W~=., replace; 
regen ID2W=1 if D2W>=0 & D2W~=., replace; 
regen Ihatd2wfe=0 if hatd2wfe<0& hatd2wfe~=., replace; 
regen Ihatd2wfe=1 if hatd2wfe>=0& hatd2wfe~=., replace; 
replace Ihatd2wfe=. if hatd2wfe==.;
replace ID2W =. if D2W==.;
tab Ihatd2wfe ID2W, all row;
tab Ihatd2wfe ID2W if abs(D2W)>.03 & abs(hatd2wfe)>.03, all row;
tab Ihatd2wfe ID2W if abs(D2W)>.03 , all row;


logit LC01 c.LW  throbhat1p throbhat2p logIncomingTenure c.LW#c.logIncomingTenure,vce(cluster ccode);
logit LCirreg01 c.LW  throbhat1p throbhat2p logIncomingTenure c.LW#c.logIncomingTenure,vce(cluster ccode);

